package str113_parsowanie_xml_DOM;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.xml.soap.Node;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class DOMTreeModel implements TreeModel {
	private Document document;
	
	/**
	 * Tworzy model drzewa dokumentu
	 * @param doc dokument
	 */
	public DOMTreeModel(Document doc) {
		this.document = doc;
	}

	@Override
	public Object getRoot() {
		return document.getDocumentElement();
	}
	
	@Override
	public int getChildCount(Object parent) {
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		return list.getLength();
	}
	
	@Override
	public Object getChild(Object parent, int index) {
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		return list.item(index);
	}

	@Override
	public boolean isLeaf(Object node) {
		return getChildCount(node) == 0;
	}
	
	@Override
	public int getIndexOfChild(Object parent, Object child) {
		Node node = (Node) parent;
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			if (getChild(node, i) == child)
					return i; 
		}
		return -1;
	}
	
	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {}

	@Override
	public void addTreeModelListener(TreeModelListener l) {}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {}

}
